package jdbcTemplate.dao.impl;

import jdbcTemplate.dao.BookDao;
import jdbcTemplate.model.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.List;

/**
 * @author wang fei
 * @date 2020-10-11 17:11
 */
@Repository
public class BookDaoImpl implements BookDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;


    public void add(Book book) {
        //1.创建sql
        String sql = "insert into user values(?,?,?)";
        //2.调用方法实现
        Object [] o = {book.getUserId(), book.getUserName(), book.getStatus()};
        int update = jdbcTemplate.update(sql,o);
        System.out.println(update + ":添加操作!!!");
    }

    public void updateBook(Book book) {
        //1.创建sql
        String sql = "update user set user_name = ? , status = ? where user_id = ?";
        //2.调用方法实现
        Object [] o = {book.getUserName(), book.getStatus(),book.getUserId()};
        int update = jdbcTemplate.update(sql,o);
        System.out.println(update + ":更改数据!!!");
    }

    public void delBook(Book book) {
        //1.创建sql
        String sql = "delete from user where user_id = ?";
        //2.调用方法实现
        Object [] o = {book.getUserId()};
        int update = jdbcTemplate.update(sql,o);
        System.out.println(update + ":删除数据!!!");
    }

    //条数
    public int foundSize() {
        //1.创建sql
        String sql = "select  count(*) from user ";
        //2.调用方法实现
        Integer update = jdbcTemplate.queryForObject(sql,Integer.class);
        System.out.println(update + ":数据条数!!!");
        return update;
    }

    //单个对象
    public Book findOne(int userId) {
        //1.创建sql
        String sql = "select * from user where user_id = ?";
        Object [] o = {userId};
        //2.调用方法实现
        Book book = jdbcTemplate.queryForObject(sql,new BeanPropertyRowMapper<Book>(Book.class),o);
        System.out.println(book.toString() + ":数据详情!!!");
        return book;
    }

    //多个对象，集合
    public List<Book> listBook() {
        //1.创建sql
        String sql = "select * from user";
        //2.调用方法实现
        List<Book> list = jdbcTemplate.query(sql,new BeanPropertyRowMapper<Book>(Book.class));
        System.out.println(Arrays.toString(list.toArray()) + ":数据详情!!!");
        return list;
    }
}
